package com.xiaoyu.util2;

import java.io.BufferedInputStream;
import java.io.BufferedOutputStream;
import java.io.BufferedReader;
import java.io.ByteArrayOutputStream;
import java.io.File;
import java.io.FileInputStream;
import java.io.FileOutputStream;
import java.io.FileReader;
import java.io.FileWriter;
import java.io.IOException;
import java.io.InputStream;
import java.io.PrintWriter;
import java.io.RandomAccessFile;
import java.net.FileNameMap;
import java.net.MalformedURLException;
import java.net.URLConnection;
import java.nio.ByteBuffer;
import java.nio.channels.FileChannel;
import java.util.ArrayList;
import java.util.Date;
import java.util.HashSet;
import java.util.List;
import java.util.Set;
import java.util.zip.ZipEntry;
import java.util.zip.ZipInputStream;
import java.util.zip.ZipOutputStream;

import com.xiaoyu.algorithmimpl.FileImpl;
import com.xiaoyu.algorithmimpl.FileTypeImpl;

public class FileUtil {
	private static Integer BUFFER_SIZE = Integer.valueOf(10485760);

	public static int countLines(File file) throws IOException {
		InputStream is = null;
		int count = 0;
		try {
			is = new BufferedInputStream(new FileInputStream(file));
			byte[] c = new byte[BUFFER_SIZE.intValue()];
			int readChars = 0;
			while ((readChars = is.read(c)) != -1)
				for (int i = 0; i < readChars; ++i)
					if (c[i] == 10)
						++count;
		} finally {
			is.close();
		}
		return count;
	}

	public static List<String> Lines(File file) {
		BufferedReader reader = null;
		List<String> list = new ArrayList<String>();
		try {
			reader = new BufferedReader(new FileReader(file));
			String line = null;
			while ((line = reader.readLine()) != null)
				list.add(line);
		} catch (IOException e) {
			e.printStackTrace();
		} finally {
			try {
				reader.close();
			} catch (IOException e) {
				e.printStackTrace();
			}
		}
		return list;
	}

	public static List<String> Lines(File file, int lines) {
		BufferedReader reader = null;
		List<String> list = new ArrayList<String>();
		try {
			reader = new BufferedReader(new FileReader(file));
			String line = null;
			do {
				if ((line = reader.readLine()) == null)
					break;
				list.add(line);
			} while (list.size() != lines);
		} catch (IOException e) {
			e.printStackTrace();
		} finally {
			try {
				reader.close();
			} catch (IOException e) {
				e.printStackTrace();
			}
		}
		return list;
	}

	public static boolean cleanFile(File file) {
		FileWriter fw = null;
		try {
			fw = new FileWriter(file);
			fw.write("");
			return true;
		} catch (IOException e) {
			e.printStackTrace();
		} finally {
			try {
				fw.close();
			} catch (Exception e) {
				e.printStackTrace();
			}
		}
		return false;
	}

	public static String MimeType(String file) throws IOException {
		FileNameMap fileNameMap = URLConnection.getFileNameMap();
		String type = fileNameMap.getContentTypeFor(file);
		return type;
	}

	public static String FileType(File file) {
		return FileTypeImpl.getFileType(file);
	}

	public static Date modifyTime(File file) {
		Date date = new Date(file.lastModified());
		return date;
	}

	public static String hash(File file) {
		return SecUtil.FileMD5(file);
	}

	public static boolean appendLine(File file, String str) {
		RandomAccessFile randomFile = null;
		try {
			randomFile = new RandomAccessFile(file, "rw");
			long fileLength = randomFile.length();
			randomFile.seek(fileLength);
			randomFile.writeBytes(str);
		} catch (IOException e) {
			e.printStackTrace();
		} finally {
			try {
				randomFile.close();
			} catch (IOException e) {
				e.printStackTrace();
			}
		}
		return false;
	}

	public static boolean copy(String resourcePath, String targetPath) {
		File file = new File(resourcePath);
		return copy(file, targetPath);
	}

	public static boolean copy(File file, String targetFile) {
		FileInputStream fin = null;
		FileOutputStream fout = null;
		try {
			fin = new FileInputStream(file);
			fout = new FileOutputStream(new File(targetFile));
			FileChannel in = fin.getChannel();
			FileChannel out = fout.getChannel();

			ByteBuffer buffer = ByteBuffer.allocate(BUFFER_SIZE.intValue());
			while (in.read(buffer) != -1) {
				buffer.flip();
				out.write(buffer);
				buffer.clear();
			}
		} catch (Throwable e) {
			e.printStackTrace();
		} finally {
			try {
				fout.close();
				fin.close();
			} catch (Exception e) {
			}
		}
		return false;
	}

	@SuppressWarnings("deprecation")
	public static String cpdetector(File file) {
		try {
			return FileImpl.cpdetector(file.toURL());
		} catch (MalformedURLException e) {
			e.printStackTrace();
		}
		return null;
	}

	public static String SimpleEncoding(String file) {
		try {
			return FileImpl.SimpleEncoding(file);
		} catch (Exception e) {
			e.printStackTrace();
		}
		return null;
	}

	public static void createPaths(String paths) {
		File dir = new File(paths);
		if (!(dir.exists()))
			dir.mkdirs();
	}

	public static boolean createFiles(String filePaht) {
		File file = new File(filePaht);
		File dir = file.getParentFile();
		if (!(dir.exists()))
			dir.mkdirs();
		try {
			file.createNewFile();
			return true;
		} catch (IOException e) {
			e.printStackTrace();
		}
		return false;
	}

	public static boolean deleteFile(File file) {
		return file.delete();
	}

	public static boolean deleteDir(File file) {
		List<File> files = listFileAll(file);
		if (ValidUtil.isValid(files)) {
			for (File f : files) {
				if (f.isDirectory())
					deleteDir(f);
				else {
					deleteFile(f);
				}
			}
		}
		return file.delete();
	}

	public static boolean deleteBigFile(File file) {
		if (cleanFile(file)) {
			return file.delete();
		}
		return false;
	}

	public static List<File> listFile(String path) {
		File file = new File(path);
		return listFile(file);
	}

	public static void copyDir(String filePath, String targetPath) {
		File file = new File(filePath);
		copyDir(file, targetPath);
	}

	public static void copyDir(File filePath, String targetPath) {
		File targetFile = new File(targetPath);
		if (!(targetFile.exists())) {
			createPaths(targetPath);
		}
		File[] files = filePath.listFiles();
		if (ValidUtil.isValid(files))
			for (File file : files) {
				String path = file.getName();
				if (file.isDirectory())
					copyDir(file, targetPath + "/" + path);
				else
					copy(file, targetPath + "/" + path);
			}
	}

	public static List<File> listFile(File path) {
		List<File> list = new ArrayList<File>();
		File[] files = path.listFiles();
		if (ValidUtil.isValid(files)) {
			for (File file : files) {
				if (file.isDirectory())
					list.addAll(listFile(file));
				else {
					list.add(file);
				}
			}
		}
		return list;
	}

	public static List<File> listFileAll(File path) {
		List<File> list = new ArrayList<File>();
		File[] files = path.listFiles();
		if (ValidUtil.isValid(files)) {
			for (File file : files) {
				list.add(file);
				if (file.isDirectory()) {
					list.addAll(listFileAll(file));
				}
			}
		}
		return list;
	}

	public static List<File> listFileFilter(File dirPath, String postfixs) {
		List<File> list = new ArrayList<File>();
		File[] files = dirPath.listFiles();
		if (ValidUtil.isValid(files)) {
			for (File file : files) {
				if (file.isDirectory()) {
					list.addAll(listFileFilter(file, postfixs));
				} else {
					String fileName = file.getName().toLowerCase();
					if (fileName.endsWith(postfixs.toLowerCase())) {
						list.add(file);
					}
				}
			}
		}
		return list;
	}

	public static List<File> searchFile(File dirPath, String fileName) {
		List<File> list = new ArrayList<File>();
		File[] files = dirPath.listFiles();
		if (ValidUtil.isValid(files)) {
			for (File file : files) {
				if (file.isDirectory()) {
					list.addAll(searchFile(file, fileName));
				} else {
					String Name = file.getName().toLowerCase();
					if (Name.equals(fileName)) {
						list.add(file);
					}
				}
			}
		}
		return list;
	}

	public static List<File> searchFileReg(File dirPath, String reg) {
		List<File> list = new ArrayList<File>();
		File[] files = dirPath.listFiles();
		if (ValidUtil.isValid(files)) {
			for (File file : files) {
				if (file.isDirectory()) {
					list.addAll(searchFile(file, reg));
				} else {
					String Name = file.getName();
					if (RegUtil.isMatche(Name, reg)) {
						list.add(file);
					}
				}
			}
		}
		return list;
	}
	
	
	//=========例外风格
	/**
     * 创建目录
     * 
     * @param dir 目录
     */
    public static void mkdir(String dir) {
        try {
            String dirTemp = dir;
            File dirPath = new File(dirTemp);
            if (!dirPath.exists()) {
                dirPath.mkdir();
            }
        } catch (Exception e) {
        	System.out.println("创建目录操作出错: "+e.getMessage());
            e.printStackTrace();
        }
    }


    /**
     * 新建文件
     * 
     * @param fileName
     *            String 包含路径的文件名 如:E:\phsftp\src\123.txt
     * @param content
     *            String 文件内容
     *            
     */
    public static void createNewFile(String fileName, String content) {
        try {
            String fileNameTemp = fileName;
            File filePath = new File(fileNameTemp);
            if (!filePath.exists()) {
                filePath.createNewFile();
            }
            FileWriter fw = new FileWriter(filePath);
            PrintWriter pw = new PrintWriter(fw);
            String strContent = content;
            pw.println(strContent);
            pw.flush();
            pw.close();
            fw.close();
        } catch (Exception e) {
            System.out.println("新建文件操作出错: "+e.getMessage());
            e.printStackTrace();
        }

    }
    
    /**
     * 删除文件
     * 
     * @param fileName 包含路径的文件名
     */
    public static void delFile(String fileName) {
        try {
            String filePath = fileName;
            java.io.File delFile = new java.io.File(filePath);
            delFile.delete();
        } catch (Exception e) {
            System.out.println("删除文件操作出错: "+e.getMessage());
            e.printStackTrace();
        }
    }
    

    /**
     * 删除文件夹
     * 
     * @param folderPath  文件夹路径
     */
    public static void delFolder(String folderPath) {
        try {
            // 删除文件夹里面所有内容
            delAllFile(folderPath); 
            String filePath = folderPath;
            java.io.File myFilePath = new java.io.File(filePath);
            // 删除空文件夹
            myFilePath.delete(); 
        } catch (Exception e) {
            System.out.println("删除文件夹操作出错"+e.getMessage());
            e.printStackTrace();
        }
    }


    /**
     * 删除文件夹里面的所有文件
     * 
     * @param path 文件夹路径
     */
    public static void delAllFile(String path) {
        File file = new File(path);
        if (!file.exists()) {
            return;
        }
        if (!file.isDirectory()) {
            return;
        }
        String[] childFiles = file.list();
        File temp = null;
        for (int i = 0; i < childFiles.length; i++) {
            //File.separator与系统有关的默认名称分隔符
            //在UNIX系统上，此字段的值为'/'；在Microsoft Windows系统上，它为 '\'。
            if (path.endsWith(File.separator)) {
                temp = new File(path + childFiles[i]);
            } else {
                temp = new File(path + File.separator + childFiles[i]);
            }
            if (temp.isFile()) {
                temp.delete();
            }
            if (temp.isDirectory()) {
                delAllFile(path + "/" + childFiles[i]);// 先删除文件夹里面的文件
                delFolder(path + "/" + childFiles[i]);// 再删除空文件夹
            }
        }
    }

    
    /**
     * 复制单个文件
     * 
     * @param srcFile
     *            包含路径的源文件 如：E:/phsftp/src/abc.txt
     * @param dirDest
     *            目标文件目录；若文件目录不存在则自动创建  如：E:/phsftp/dest
     * @throws IOException
     */
    public static void copyFile(String srcFile, String dirDest) {
        try {
            FileInputStream in = new FileInputStream(srcFile);
            mkdir(dirDest);
            FileOutputStream out = new FileOutputStream(dirDest+"/"+new File(srcFile).getName());
            int len;
            byte buffer[] = new byte[1024];
            while ((len = in.read(buffer)) != -1) {
                out.write(buffer, 0, len);
            }
            out.flush();
            out.close();
            in.close();
        } catch (Exception e) {
            System.out.println("复制文件操作出错:"+e.getMessage());
            e.printStackTrace();
        }
    }

    /**
     * 复制文件夹
     * 
     * @param oldPath
     *            String 源文件夹路径 如：E:/phsftp/src
     * @param newPath
     *            String 目标文件夹路径 如：E:/phsftp/dest
     * @return boolean
     */
    public static void copyFolder(String oldPath, String newPath) {
        try {
            // 如果文件夹不存在 则新建文件夹
            mkdir(newPath);
            File file = new File(oldPath);
            String[] files = file.list();
            File temp = null;
            for (int i = 0; i < files.length; i++) {
                if (oldPath.endsWith(File.separator)) {
                    temp = new File(oldPath + files[i]);
                } else {
                    temp = new File(oldPath + File.separator + files[i]);
                }

                if (temp.isFile()) {
                    FileInputStream input = new FileInputStream(temp);
                    FileOutputStream output = new FileOutputStream(newPath
                            + "/" + (temp.getName()).toString());
                    byte[] buffer = new byte[1024 * 2];
                    int len;
                    while ((len = input.read(buffer)) != -1) {
                        output.write(buffer, 0, len);
                    }
                    output.flush();
                    output.close();
                    input.close();
                }
                if (temp.isDirectory()) {// 如果是子文件夹
                    copyFolder(oldPath + "/" + files[i], newPath + "/" + files[i]);
                }
            }
        } catch (Exception e) {
            System.out.println("复制文件夹操作出错:"+e.getMessage());
            e.printStackTrace();
        }
    }
    
    /**
     * 移动文件到指定目录
     * 
     * @param oldPath 包含路径的文件名 如：E:/phsftp/src/ljq.txt
     * @param newPath 目标文件目录 如：E:/phsftp/dest
     */
    public static void moveFile(String oldPath, String newPath) {
        copyFile(oldPath, newPath);
        delFile(oldPath);
    }
    
    /**
     * 移动文件到指定目录，不会删除文件夹
     * 
     * @param oldPath 源文件目录  如：E:/phsftp/src
     * @param newPath 目标文件目录 如：E:/phsftp/dest
     */
    public static void moveFiles(String oldPath, String newPath) {
        copyFolder(oldPath, newPath);
        delAllFile(oldPath);
    }
    
    /**
     * 移动文件到指定目录，会删除文件夹
     * 
     * @param oldPath 源文件目录  如：E:/phsftp/src
     * @param newPath 目标文件目录 如：E:/phsftp/dest
     */
    public static void moveFolder(String oldPath, String newPath) {
        copyFolder(oldPath, newPath);
        delFolder(oldPath);
    }
    
	/**
	 * 
	 * @param dir
	 *            需要遍历的目录
	 * @param fileList
	 *            存放符合条件的容器
	 */
	public static void getFileList(File dir, List<File> fileList) {
		if (dir.exists()) {
			File[] files = dir.listFiles();// 找到目录下面的所有文件
			for (File file : files) {
				// 递归
				if (file.isDirectory()) {
					getFileList(file, fileList);
				} else {
					// 对遍历的文件进行过滤，符合条件的放入List集合中
					if (file.getName().endsWith(".zip")) {// 过滤满足条件的文件 先.zip
						fileList.add(file);
					}
				}
			}
		} else {
			// 对遍历的文件进行过滤，符合条件的放入List集合中
			if (dir.getName().endsWith(".zip")) {// 过滤满足条件的文件 先.zip
				fileList.add(dir);
			}
		}
	}
    
    /**
     * 解压zip文件
     * 
     * @param srcDir
     *            解压前存放的目录
     * @param destDir
     *            解压后存放的目录
     * @throws Exception
     */
    public static void jieYaZip(String srcDir, String destDir) throws Exception {
        int leng = 0;
        byte[] b = new byte[1024*2];
        List<File> fileList = new ArrayList<File>();
        /** 获取zip格式的文件 **/
        getFileList(new File(srcDir), fileList);
        if(fileList!=null && !fileList.isEmpty()){
            for (int i = 0; i < fileList.size(); i++) {
                File file = fileList.get(i);
                /** 解压的输入流 * */
                ZipInputStream zis = new ZipInputStream(new FileInputStream(file));
                ZipEntry entry=null;
                while ((entry=zis.getNextEntry())!=null) {
                    File destFile =null;
                    if(destDir.endsWith(File.separator)){
                        destFile = new File(destDir + entry.getName());
                    }else {
                        destFile = new File(destDir + "/" + entry.getName());
                    }
                    /** 把解压包中的文件拷贝到目标目录 * */
                    FileOutputStream fos = new FileOutputStream(destFile);
                    while ((leng = zis.read(b)) != -1) {
                        fos.write(b, 0, leng);
                    }
                    fos.close();
                }
                zis.close();
            }
        }
    }
    
    /**
     * 压缩文件
     * 
     * @param srcDir
     *            压缩前存放的目录
     * @param destDir
     *            压缩后存放的目录
     * @throws Exception
     */
    public static void yaSuoZip(String srcDir, String destDir) throws Exception {
        String tempFileName=null;
        byte[] buf = new byte[1024*2];
        int len;
        //获取要压缩的文件
        File[] files = new File(srcDir).listFiles();
        if(files!=null){
            for (File file : files) {
                if(file.isFile()){
                    FileInputStream fis = new FileInputStream(file);
                    BufferedInputStream bis = new BufferedInputStream(fis);
                    if (destDir.endsWith(File.separator)) {
                        tempFileName = destDir + file.getName() + ".zip";
                    } else {
                        tempFileName = destDir + "/" + file.getName() + ".zip";
                    }
                    FileOutputStream fos = new FileOutputStream(tempFileName);
                    BufferedOutputStream bos = new BufferedOutputStream(fos);
                    ZipOutputStream zos = new ZipOutputStream(bos);// 压缩包

                    ZipEntry ze = new ZipEntry(file.getName());// 压缩包文件名
                    zos.putNextEntry(ze);// 写入新的ZIP文件条目并将流定位到条目数据的开始处

                    while ((len = bis.read(buf)) != -1) {
                        zos.write(buf, 0, len);
                        zos.flush();
                    }
                    bis.close();
                    zos.close();
                }
            }
        }
    }
    
    
    /**
     * 读取数据
     * 
     * @param inSream
     * @param charsetName
     * @return
     * @throws Exception
     */
    public static String readData(InputStream inSream, String charsetName) throws Exception{
        ByteArrayOutputStream outStream = new ByteArrayOutputStream();
        byte[] buffer = new byte[1024];
        int len = -1;
        while( (len = inSream.read(buffer)) != -1 ){
            outStream.write(buffer, 0, len);
        }
        byte[] data = outStream.toByteArray();
        outStream.close();
        inSream.close();
        return new String(data, charsetName);
    }
    
    /**
     * 一行一行读取文件，适合字符读取，若读取中文字符时会出现乱码
     * 
     * @param path
     * @return
     * @throws Exception
     */
    public static Set<String> readFile(String path) throws Exception{
        Set<String> datas=new HashSet<String>();
        FileReader fr=new FileReader(path);
        BufferedReader br=new BufferedReader(fr);
        String line=null;
        while ((line=br.readLine())!=null) {
            datas.add(line);
        }
        br.close();
        fr.close();
        return datas;
    }
    
}